package controller.manager;

import controller.movieSectionManipulation.MovieSectionSorting;
import databaseLayer.House_db;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.MovieSection;
import util.HibernateUtil;
import databaseLayer.MovieSection_db;

public class MovieManagementServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter("action");

        if (action == null) {
            defaultAction(request, response);
        } else if (action.equalsIgnoreCase("search")) {
            searchMovieSections(request, response);
        } else if (action.equalsIgnoreCase("create")) {
            createMovieSection(request, response);
        } else if (action.equalsIgnoreCase("delete")) {
            deleteMovieSection(request, response);
        } else if (action.equalsIgnoreCase("update")) {
            updateMovieSection(request, response);
        } else {
            defaultAction(request, response);
        }
    }

    private void defaultAction(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();

        List<String> listHouseId = House_db.selectAllHouseIds();
        session.setAttribute("listHouseId", listHouseId);

        List<String> listMovieName = MovieSection_db.selectAllMovieNames();
        session.setAttribute("listMovieName", listMovieName);

        String[] arrSortBy = MovieSectionSorting.allSortBys();
        session.setAttribute("arrSortBy", arrSortBy);
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/listMovieSections.jsp");
        requestDispatcher.forward(request, response);
    }

    private void updateMovieSection(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        MovieSection target = null;
        try {
            String secondTime = request.getParameter("secondTime");
            String id = request.getParameter("id");
            target = MovieSection_db.selectMovieSectionById(id);
            if (secondTime == null) {
                HttpSession session = request.getSession();
                session.setAttribute("targetMovieSection", target);
                RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/updateMovieSectionInput.jsp");
                requestDispatcher.forward(request, response);
            } else {
                String movieName = request.getParameter("movieName");
                String strPrice = request.getParameter("price");
                String strStartTime = request.getParameter("startTime");
                String strDuration = request.getParameter("duration");
                String houseId = request.getParameter("houseId");

                // check empty input
                if (movieName == null || movieName.equals("")
                        || strPrice == null || strPrice.equals("")
                        || strStartTime == null || strStartTime.equals("")
                        || strDuration == null || strDuration.equals("")
                        || houseId == null || houseId.equals("")) {
                    throw new Exception("Some field is empty");
                }

                // date formating
                DateFormat standardFormat = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm");
                Date startTime = standardFormat.parse(strStartTime);

                // update
                target.setMovieName(movieName);
                target.setPrice(Integer.parseInt(strPrice));
                target.setStartTime(startTime);
                target.setDuration(Integer.parseInt(strDuration));
                target.setHouseId(houseId);

                boolean success = HibernateUtil.update(target);
                if (success == false) {
                    throw new Exception("Fail to update");
                }

                // forward to JSP
                HttpSession session = request.getSession();
                session.setAttribute("message",
                        "Update a new movie section successfully");
                RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/manipulateResult.jsp");
                requestDispatcher.forward(request, response);
            }
        } catch (Exception ex) {
            String message = ex.getMessage();
            HttpSession session = request.getSession();
            session.setAttribute("message", message);
            session.setAttribute("targetMovieSection", target);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/updateMovieSectionInput.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    private void deleteMovieSection(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            MovieSection target = MovieSection_db.selectMovieSectionById(id);
            boolean isSuccess = HibernateUtil.delete(target);
            if (isSuccess == false) {
                throw new Exception("Fail to delete. Someone has already bought the ticket for this movie section");
            }
            HttpSession session = request.getSession();
            session.setAttribute("message", "Delete a movie section successfully");
        } catch (Exception e) {
            HttpSession session = request.getSession();
            session.setAttribute("message", e.getMessage());
        } finally {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/manipulateResult.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    private void createMovieSection(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            String movieName = request.getParameter("movieName");
            String strPrice = request.getParameter("price");
            String strStartTime = request.getParameter("startTime");
            String strDuration = request.getParameter("duration");
            String houseId = request.getParameter("houseId");

            // check empty input
            if (movieName == null || movieName.equals("") || strPrice == null
                    || strPrice.equals("") || strStartTime == null
                    || strStartTime.equals("") || strDuration == null
                    || strDuration.equals("") || houseId == null
                    || houseId.equals("")) {
                throw new Exception("Some fields are empty! Please check carefully and create again!");
            }

            // date formating
            DateFormat standardFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date startTime = standardFormat.parse(strStartTime);

            // insert new movie
            MovieSection newMovieSection = new MovieSection(movieName,
                    Integer.parseInt(strPrice), startTime,
                    Integer.parseInt(strDuration), houseId);
            boolean success = HibernateUtil.insert(newMovieSection);
            if (success == false) {
                throw new Exception("Fail to create");
            }
            HttpSession session = request.getSession();
            session.setAttribute("message", "Create a new movie section successfully!");
        } catch (Exception e) {
            HttpSession session = request.getSession();
            session.setAttribute("message", e.getMessage());
        } finally {
            // forward to JSP
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/manipulateResult.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    private void searchMovieSections(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String movieName = request.getParameter("movieName");
        List<MovieSection> listMovieSection = null;
        if (movieName.equals("(all)")) {
            listMovieSection = MovieSection_db.selectAllMovieSections();
        } else {
            listMovieSection = MovieSection_db.selectMovieSectionsByMovieName(movieName);
        }
        String sortBy = request.getParameter("sortBy");
        MovieSectionSorting.getInstance().sortMovieSection(listMovieSection, sortBy);
        session.setAttribute("listMovieSection", listMovieSection);

        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/manager/movieManagement/listMovieSections.jsp");
        requestDispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MovieManagementServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
}
